package com.gao.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.gao.dao.UserDao;
import com.gao.domain.User;
import com.gao.util.DBUtil;

public class UserDaoImpl implements UserDao{

	@Override
	public User findUserByUsernameAndPassword(String username, String password) throws SQLException {
		User user = null;
		Connection conn = DBUtil.getConnection();
	    String sql = "select * from user where username=? and password=?";
	    PreparedStatement pstmt = conn.prepareStatement(sql);
	    pstmt.setString(1, username);
	    pstmt.setString(2, password);
	    ResultSet rs = pstmt.executeQuery();
	    if(rs.next()){//?????????
	    	user = new User(rs.getInt("uid"),username,rs.getString("password"),rs.getString("phonenum"));
	    }
	    DBUtil.release(rs,pstmt, conn);
//		System.out.println(user);
		return user;
	}

	@Override
	public boolean addUser(String username, String password, String phonenum) throws SQLException {
		boolean flag = false;
		Connection conn = DBUtil.getConnection();
	    String sql = "insert into user values(null,?,?,?)";
	    PreparedStatement pstmt = conn.prepareStatement(sql);
	    pstmt.setString(1, username);
	    pstmt.setString(2, password);
	    pstmt.setString(3, phonenum);
	    int num = pstmt.executeUpdate();
	    if(num>0){
	    	flag = true;
	    }
	    DBUtil.release(pstmt, conn);
		return flag;
	}

	@Override
	public User findUserByUsername(String username) throws SQLException {
		User user = null;
		Connection conn = DBUtil.getConnection();
	    String sql = "select * from user where username=?";
	    PreparedStatement pstmt = conn.prepareStatement(sql);
	    pstmt.setString(1, username);
	    ResultSet rs = pstmt.executeQuery();
	    if(rs.next()){//?????????
	    	user = new User(rs.getInt("uid"),username,rs.getString("password"),rs.getString("phonenum"));
	    }
		//????5????????
	    DBUtil.release(rs,pstmt, conn);
		return user;
	}
	

}
